package org.noote.libs.graphicbuffer;

public class FPSCounter {
	
	protected boolean _bIntervalCounting=false;
    protected float _fIntervalTiming=1.0f; // precalcul at each second
    
    protected long _iIntervalFrameCounter=0;
    protected float _fIntervalTimeCounter=0;
    
    protected long _iFrameCounter=0;
    protected float _fTimeCounter=0;
    
    protected float fFPS = 0;
    protected long uTime=0;
    
    protected float _fLastTimeSlice = 0;
    
    public FPSCounter()
    {
    	_bIntervalCounting=false;
    }
    
    public FPSCounter(float fTiming)
    {
    	_fIntervalTiming = fTiming;
    	_bIntervalCounting=true;
    }
    
    public float getLastTimeSlice()
    {
    	return _fLastTimeSlice;
    }

    public float getFPS()
    {
    	if(_bIntervalCounting)
    		return fFPS;
    	
    	return getGlobalFPS();
    }
    
    public float getGlobalTimeCount()
    {
    	return _fTimeCounter;
    }
    
    public long getGlobalFrameCount()
    {
    	return _iFrameCounter;
    }
    
    public float getGlobalFPS()
    {
    	if(_iFrameCounter==0 || _fTimeCounter==0) return 0;
    	return _iFrameCounter/_fTimeCounter;
    }
    
    
    public void reset()
    {
    	fFPS = 0;
    	_iFrameCounter = 0;
    	_fTimeCounter = 0;
    	_iIntervalFrameCounter = 0;
    	_fIntervalTimeCounter=0;
    	uTime=0;
    }
    
    public boolean update(float fTimeSlice)
    {
    	_fLastTimeSlice = fTimeSlice;
    	
    	if(_bIntervalCounting)
    	{
	    	_iIntervalFrameCounter++;
	    	_fIntervalTimeCounter+=fTimeSlice;
	    	
	    	// precalcul FPS
	        if(_fIntervalTimeCounter>_fIntervalTiming)
	        {
	        	if(_iIntervalFrameCounter==0 || _fIntervalTimeCounter==0) fFPS=0;
	        	else fFPS = _iIntervalFrameCounter/_fIntervalTimeCounter;
	        	_iIntervalFrameCounter = 0;
	        	_fIntervalTimeCounter=0;
	        	return true;
	        }
	        
	        return false;
    	}
        
        _iFrameCounter++;
        _fTimeCounter+=fTimeSlice;
        
        return true;
    }

    public float getTimeSlice()
    {
		long _now=System.currentTimeMillis();
		if(uTime == 0) uTime=_now;
		return (_now - uTime)/1000.0f;
    }

    public boolean tick()
    {
		long _now=System.currentTimeMillis();
		if(uTime == 0) uTime=_now;
		float fTimeSlice=(_now - uTime)/1000.0f;
		uTime = _now;
		
        return update(fTimeSlice);
    }
}
